import tempfile

class FitParameterTeXTable(object):
    col3header = r"\begin{tabular}{lll}"
#    group_header = r"\begin{{center}}{0}\end{{center}}"
    group_header = r"{0}\\"
    col3param  = "\t" + r"${0}$ &= {1:> .4g}&$\pm${2:.3g}{3}"

    close_table = r"\end{tabular}" + "\n"
    vskip = r"\vskip 1mm"
    hline = "\t" + r"\hline"

    chi2header = r"\begin{tabular}{ll}"
    chi2i = "\t" + r"Initial $\chi^2$/d.o.f.:& {0:.3f} \\"
    chi2f = "\t" + r"Final $\chi^2$/d.o.f.:& {0:.3f}"

    def __init__(self):        
        self.buffer = []

    def add_group(self, group, header=None):
        if header is not None:
            self.buffer.append(FitParameterTeXTable.group_header.format(header))
            self.buffer.append(FitParameterTeXTable.col3header)
            self.buffer.append(FitParameterTeXTable.hline)
        else:
            self.buffer.append(FitParameterTeXTable.col3header)

        return_chars = [r'\\']*len(group)
#        return_chars[-1] = ''
        for i, param in enumerate(group):
            self.buffer.append(FitParameterTeXTable.col3param.format(param[0],
                                                                     param[1],
                                                                     param[2],
                                                                     return_chars[i]))

#        self.buffer.append(FitParameterTeXTable.hline)
        self.buffer.append(FitParameterTeXTable.close_table)
        self.buffer.append(FitParameterTeXTable.vskip)

    def add_chi2(self, chi2i, chi2f):
        self.buffer.append(FitParameterTeXTable.chi2header)
        self.buffer.append(FitParameterTeXTable.chi2i.format(chi2i))
        self.buffer.append(FitParameterTeXTable.chi2f.format(chi2f))
        self.buffer.append(FitParameterTeXTable.close_table)


    def write(self):
        tf = tempfile.NamedTemporaryFile(suffix='.tex')

#        tf = open("/scratch/tmp.tex", 'w')

        if self.buffer[-1] == FitParameterTeXTable.vskip:
            tf.write('\n'.join(self.buffer[:-1]))    
        else:
            tf.write('\n'.join(self.buffer))
        
        tf.write('\n')
        tf.flush()
        tf.seek(0)

        return tf
            
